<template>
  <je-modal
    v-model:visible="visible"
    class="people-choose-value-config"
    width="1200px"
    :title="title"
    :resize="false"
    :maximizable="false"
    cancel-button
    :ok-button="handleOk"
    @close="handleClose"
  >
    <je-form
      ref="formRef"
      class="form"
      :rules="rules"
      :model="formState"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      size="small"
    >
      <je-collapse v-model:activeKey="activeKey" expand-icon-position="right">
        <je-collapse-panel key="1" header="核心配置">
          <je-row>
            <je-col :span="8">
              <je-form-item label="目标功能" name="funcName">
                <!-- <div class="inputWrap">
                  <je-input v-model:value="formState.funcName" />
                  <i class="setIcon fal fa-cog"></i>
                </div>  -->
                <je-grid-select
                  v-model:value="formState.funcName"
                  disabled
                  name="funcName"
                  config-info="JE_CORE_FUNCINFO,funcName~funcCode~funcId,FUNCINFO_FUNCNAME~FUNCINFO_FUNCCODE~JE_CORE_FUNCINFO_ID,S"
                  :querys="funcQueryName"
                  @select="selectfuncNameRow"
                /> </je-form-item
            ></je-col>
            <je-col :span="8">
              <je-form-item label="功能编码" name="funcCode">
                <je-input v-model:value="formState.funcCode" disabled />
              </je-form-item>
            </je-col>
            <je-col :span="8">
              <je-form-item label="选择模式" name="selModel">
                <je-radio-group v-model:value="formState.selModel" style="margin-top: 5px">
                  <je-radio value="S">单选(s)</je-radio>
                  <je-radio value="M">多选(m)</je-radio>
                </je-radio-group>
              </je-form-item></je-col
            >
          </je-row>

          <je-row>
            <je-col :span="16">
              <je-form-item label="禁用过滤方式" name="queryType">
                <je-checkbox-group
                  v-model:value="formState.queryType"
                  style="width: 100%"
                  :options="
                    [
                      { key: 'common', title: '常用' },
                      { key: 'dept', title: '部门' },
                      { key: 'role', title: '角色' },
                      { key: 'organ', title: '机构' },
                    ].map((item) => ({ label: item.title, value: item.key }))
                  "
                />
              </je-form-item>
            </je-col>
          </je-row>

          <je-row>
            <je-col :span="8">
              <je-form-item name="deptQuery">
                <template #label>
                  <div
                    class="iconWrap"
                    @click="
                      showModal({
                        type: 'SqlFilter',
                        title: '过滤配置',
                        key: 'deptQuery',
                        value: formState.deptQuery,
                        funcId: 'QGaw1wSFgQukrj2OoSd',
                      })
                    "
                  >
                    <i
                      class="fal fa-filter"
                      :style="`color:${formState.deptQuery ? '#F4CE4A' : '#8d98ab'}`"
                    ></i>
                    部门过滤条件
                  </div>
                </template>
                <je-input v-model:value="formState.deptQuery" /> </je-form-item
            ></je-col>
            <je-col :span="8">
              <je-form-item name="roleQuery">
                <template #label>
                  <div
                    class="iconWrap"
                    @click="
                      showModal({
                        type: 'SqlFilter',
                        title: '过滤配置',
                        key: 'roleQuery',
                        value: formState.roleQuery,
                        funcId: 'kdMlrNfdR0bGlLXMxaV',
                      })
                    "
                  >
                    <i
                      class="fal fa-filter"
                      :style="`color:${formState.roleQuery ? '#F4CE4A' : '#8d98ab'}`"
                    ></i>
                    角色过滤条件
                  </div>
                </template>
                <je-input v-model:value="formState.roleQuery" /> </je-form-item
            ></je-col>
            <je-col :span="8">
              <je-form-item name="organQuery">
                <template #label>
                  <div
                    class="iconWrap"
                    @click="
                      showModal({
                        type: 'SqlFilter',
                        title: '过滤配置',
                        key: 'organQuery',
                        value: formState.organQuery,
                        funcId: '2dOfgk9pNWUt2XXen6D',
                      })
                    "
                  >
                    <i
                      class="fal fa-filter"
                      :style="`color:${formState.organQuery ? '#F4CE4A' : '#8d98ab'}`"
                    ></i>
                    机构过滤条件
                  </div>
                </template>
                <je-input v-model:value="formState.organQuery" /> </je-form-item
            ></je-col>
          </je-row>
          <je-form-item label="条件说明" name="querySqlDesc">
            <je-input v-model:value="formState.querySqlDesc">
              <!-- <template #addonAfter>
                <div style="cursor: pointer; color: rgb(83, 149, 0)" @click="handleTranslate"
                  >自然语言智能翻译</div
                >
              </template> -->
            </je-input>
          </je-form-item>
        </je-collapse-panel>

        <je-collapse-panel key="2" header="带值规则">
          <div class="tableWrap">
            <je-table
              class="table"
              border
              show-overflow
              keep-source
              sync-resize
              draggable
              auto-resize
              :style="`height: ${tableHeight}`"
              :scroll-y="{ mode: 'wheel' }"
              :edit-config="{
                trigger: 'click',
                mode: 'cell',
              }"
              :store="codes"
              size="mini"
              header-align="center"
              @drop="codesArrDrop"
            >
              <je-table-column field="index" title="序号" width="50" align="center">
              </je-table-column>
              <!-- <je-table-column field="pkName" title="唯一" width="50" align="center">
                <template #default="{ row }">
                  <je-checkbox v-model:checked="row.pkName" />
                </template>
              </je-table-column> -->
              <je-table-column field="name" title="目标功能字段">
                <template #edit="{ row }">
                  <je-input v-model:value="row.name" disabled />
                </template>
              </je-table-column>
              <je-table-column field="code" title="字段编码" width="220">
                <template #edit="{ row }">
                  <je-input v-model:value="row.code" disabled />
                </template>
              </je-table-column>
              <je-table-column width="50" align="center">
                <template #header>
                  <i
                    style="font-size: 16px; cursor: pointer"
                    class="fal fa-plus"
                    @click="addColumn"
                  ></i>
                </template>
                <template #default="{ row }">
                  <i
                    style="font-size: 16px; cursor: pointer"
                    class="fal fa-times"
                    @click="deleteColumn('codes', row)"
                  ></i>
                </template>
              </je-table-column>
            </je-table>

            <je-table
              class="table"
              border
              show-overflow
              keep-source
              draggable
              :style="`height: ${tableHeight}`"
              :scroll-y="{ mode: 'wheel' }"
              :edit-config="{
                trigger: 'click',
                mode: 'cell',
                showUpdateStatus: true,
              }"
              :store="selfCodes"
              size="mini"
              header-align="center"
              @drop="selfCodesArrDrop"
            >
              <je-table-column field="index" title="序号" width="50" align="center">
              </je-table-column>
              <je-table-column field="name" title="本功能字段">
                <template #edit="{ row }">
                  <je-input v-model:value="row.name" disabled />
                </template>
              </je-table-column>
              <je-table-column field="code" title="字段编码" width="220">
                <template #edit="{ row }">
                  <je-input v-model:value="row.code" disabled />
                </template>
              </je-table-column>
              <je-table-column width="50" align="center">
                <template #header>
                  <i
                    style="font-size: 16px; cursor: pointer"
                    class="fal fa-plus"
                    @click="addColumnSelf"
                  ></i>
                </template>
                <template #default="{ row }">
                  <i
                    style="font-size: 16px; cursor: pointer"
                    class="fal fa-times"
                    @click="deleteColumn('selfCodes', row)"
                  ></i>
                </template>
              </je-table-column>
            </je-table>
          </div>
          <template #extra
            ><i
              :class="[activeKey.length > 1 ? 'jeicon jeicon-an' : 'jeicon jeicon-packup']"
              style="padding-right: 30px; cursor: pointer"
              @click="handleClick"
            ></i
          ></template>
        </je-collapse-panel>
      </je-collapse>
    </je-form>

    <div v-if="modalOption.modalFlag">
      <component
        :is="modalOption.activeModal"
        :visble="modalOption.modalFlag"
        :record-data="modalOption.recordData"
        @btnClick="btnClick"
      ></component>
    </div>
  </je-modal>
</template>

<script>
  import { ref, toRefs, reactive, defineComponent, onMounted, watch, nextTick } from 'vue';
  import { Collapse, Row, Col } from 'ant-design-vue';

  // import SqlFilter from '@/components/form-field-config/components/sql-filter.vue';

  import {
    Grid,
    Modal,
    InputSelect,
    Form,
    Input,
    Select,
    Checkbox,
    Radio,
    Data,
  } from '@jecloud/ui';

  import { decode, encode, isNotEmpty } from '@jecloud/utils';

  import { SelectWindow } from '@jecloud/func';
  // import { sqlEditorModal } from '@/helper/index.js';
  import { showFuncQuerys } from '@jecloud/func';

  import {
    getData as FuncDetail,
    ListFieldConfigGet as FuncField,
    ChangeTranslateSql,
  } from '@/api/index';

  // import { useFuncStore } from '@/store/func-store';

  export default defineComponent({
    name: 'PeopleChooseValueConfig',
    components: {
      JeModal: Modal,
      JeCollapse: Collapse,
      JeCollapsePanel: Collapse.Panel,
      JeRow: Row,
      JeCol: Col,
      JeForm: Form,
      JeFormItem: Form.Item,
      JeInput: Input,
      JeSelect: Select,
      JeSelectOption: Select.Option,
      JeCheckbox: Checkbox,
      JeCheckboxGroup: Checkbox.Group,
      JeRadio: Radio,
      JeRadioGroup: Radio.Group,
      JeTable: Grid,
      JeTableColumn: Grid.Column,
      // SqlFilter,
      JeGridSelect: InputSelect.Grid,
      JeTreeSelect: InputSelect.Tree,
    },
    props: {
      visble: {
        type: Boolean,
        default: false,
      },
      recordData: {
        type: Object,
        default: () => {},
      },
    },
    emits: ['changeModal'],
    setup(props, { emit }) {
      // const funcStore = useFuncStore();
      const state = reactive({
        visible: props.visble,
        title: props.recordData.title,
        activeKey: ['1', '2'],
        tableHeight: `calc(100vh - 520px)`,
        formRef: ref(),
        formState: props.recordData,
        defaultValue: '默认列表方案',
        labelCol: {
          style: { width: '130px' },
        },
        wrapperCol: {},
        rules: {},
        selfCodes: Data.Store.useGridStore({
          data: [],
        }),
        codes: Data.Store.useGridStore({
          data: [],
        }),
        JE_CORE_FUNCINFO_ID: [], // 目标功能ID
        funcQueryName: [
          {
            code: 'FUNCINFO_FUNCTYPE',
            type: 'in',
            value: ['TREE', 'FUNC', 'VIEW'],
            cn: 'and',
          },
        ],
      });

      const modalOption = reactive({
        modalFlag: false, // 默认modal都是隐藏的false
        activeModal: '', // 默认没有激活的弹窗类型
      });

      const methods = {
        // 拖拽排序目标功能字段
        codesArrDrop() {
          state.codes.data.forEach((item, index_) => {
            item.index = index_ + 1;
          });
        },
        // 本功能字段
        selfCodesArrDrop() {
          state.selfCodes.data.forEach((item, index_) => {
            item.index = index_ + 1;
          });
        },
        handleClick(event) {
          if (state.activeKey.length == 1) {
            state.activeKey = ['1', '2'];
            state.tableHeight = `calc(100vh - 520px)`;
          } else {
            state.activeKey = ['2'];
            state.tableHeight = `calc(100vh - 340px)`;
          }

          event.stopPropagation();
        },
        // 选择目标功能，获取功能Id
        selectfuncNameRow({ rows }) {
          if (rows && rows.length) {
            state.JE_CORE_FUNCINFO_ID = rows[0].JE_CORE_FUNCINFO_ID;
          }
        },
        handleClose() {
          state.visible = false;
          emit('changeModal', { visible: false });
        },

        handleOk() {
          let { funcCode, selModel } = state.formState;
          let cfgs = {};
          let otherCfgs = state.otherCfgs;
          let pkNames = [];

          cfgs = [funcCode, [], [], selModel];

          state.selfCodes.data.forEach((item) => {
            cfgs[1].push(item.code);
          });
          cfgs[1] = cfgs[1].join('~');

          state.codes.data.forEach((item) => {
            if (item.pkName) {
              pkNames.push(item.code);
            }
            cfgs[2].push(item.code);
          });
          cfgs[2] = cfgs[2].join('~');
          cfgs = cfgs.join(',');

          if (state.codes.data.length !== state.selfCodes.data.length) {
            Modal.alert('两组字段对应的条数不相同，请重新选择！', 'warning');
            return false;
          }

          if (pkNames.length > 1) {
            Modal.alert('字段唯一标识只能选择一个！', 'warning');
            return false;
          } else {
            otherCfgs.pkName = pkNames[0] || '';
          }
          otherCfgs.queryType = state.formState.queryType || '';
          otherCfgs.roleQuery = state.formState.roleQuery || '';
          otherCfgs.organQuery = state.formState.organQuery || '';
          otherCfgs.deptQuery = state.formState.deptQuery || '';
          otherCfgs.querySqlDesc = state.formState.querySqlDesc || '';
          state.visible = false;
          emit('changeModal', {
            type: 'PeopleChooseValueConfig',
            visible: false,
            data: {
              RESOURCEFIELD_CONFIGINFO: cfgs,
              RESOURCEFIELD_WHERESQL: state.formState.RESOURCEFIELD_WHERESQL,
              RESOURCEFIELD_OTHERCONFIG: encode(otherCfgs),
            },
          });

          return false;
        },

        showModal(obj) {
          showFuncQuerys({
            value: state.formState[obj.key],
            funcId: obj.funcId,
            configInfo: 'JE_CORE_TABLECOLUMN,code,TABLECOLUMN_CODE,S',
            querys: [{ code: 'TABLECOLUMN_RESOURCETABLE_ID', type: '=', value: obj.funcId }],
            callback: (value) => {
              state.formState[obj.key] = value;
            },
          });
        },

        btnClick(obj) {
          modalOption.modalFlag = false;

          if (obj.type === 'ok') {
            state.formState[modalOption.key] = obj.value;
          }
        },

        // 目标功能添加字段
        addColumn() {
          if (!state.formState.funcName) {
            Modal.alert('请先选择目标功能在进行字段添加！', 'info');
            return false;
          }
          // 目标功能中字段的选择
          SelectWindow.show({
            title: '目标功能字段',
            type: 'grid',
            orders: [
              // { code: 'TABLECOLUMN_CLASSIFY', type: 'ASC' },
              { code: 'SY_ORDERINDEX', type: 'ASC' },
            ],
            querys: [
              {
                code: 'RESOURCECOLUMN_FUNCINFO_ID',
                value: state.formState.funcId,
                type: '=',
                cn: 'and',
              },
              {
                code: 'RESOURCECOLUMN_XTYPE',
                value: 'uxcolumn',
                type: '=',
                cn: 'and',
              },
              // { code: 'TABLECOLUMN_ISCREATE', type: '=', value: '1', cn: 'and' },
            ],
            configInfo: 'JE_CORE_RESOURCECOLUMN,,,M',
            callback: function ({ rows }) {
              //  对选择数据进行处理，变成code , text
              if (rows && rows.length) {
                const data = [];
                rows.forEach((item, index) => {
                  const { RESOURCECOLUMN_CODE, RESOURCECOLUMN_NAME } = item;
                  data.push({
                    code: RESOURCECOLUMN_CODE,
                    name: RESOURCECOLUMN_NAME,
                    pkNames: false,
                    index: state.codes.data.length + 1 + index,
                  });
                });
                state.codes.insert(data, -1);
              }
            },
          });
        },
        // 本功能添加字段
        addColumnSelf() {
          // 本功能ID： state.formState.RESOURCEFIELD_FUNCINFO_ID
          //列表现有的code值
          const columnCode = [];
          state.selfCodes.data.forEach((item) => {
            columnCode.push(item.code);
          });

          SelectWindow.show({
            title: '本功能字段',
            type: 'grid',
            orders: [
              // { code: 'TABLECOLUMN_CLASSIFY', type: 'ASC' },
              { code: 'SY_ORDERINDEX', type: 'ASC' },
            ],
            querys: [
              {
                code: 'RESOURCECOLUMN_FUNCINFO_ID',
                value: state.formState.RESOURCEFIELD_FUNCINFO_ID,
                type: '=',
                cn: 'and',
              },
              {
                code: 'RESOURCECOLUMN_CODE',
                value: columnCode,
                type: 'notIn',
                cn: 'and',
              },
              {
                code: 'RESOURCECOLUMN_XTYPE',
                value: 'uxcolumn',
                type: '=',
                cn: 'and',
              },
              // { code: 'TABLECOLUMN_ISCREATE', type: '=', value: '1', cn: 'and' },
            ],
            configInfo: 'JE_CORE_RESOURCECOLUMN,,,M',
            callback: function ({ rows, config, $modal }) {
              //  对选择数据进行处理，变成code , text
              if (rows && rows.length) {
                const data = [];
                rows.forEach((item, index) => {
                  const { RESOURCECOLUMN_CODE, RESOURCECOLUMN_NAME } = item;
                  // pkNames目前不知道这个字段是干嘛用的
                  data.push({
                    code: RESOURCECOLUMN_CODE,
                    name: RESOURCECOLUMN_NAME,
                    pkNames: false,
                    index: state.selfCodes.data.length + index + 1,
                  });
                });
                state.selfCodes.insert(data, -1);
              }
            },
          });
        },

        deleteColumn(key, row) {
          state[key].remove(row);
        },

        async getFuncDetail() {
          const params = {
            tableCode: 'JE_CORE_FUNCINFO',
            limit: 1,
            j_query: JSON.stringify({
              custom: [
                {
                  code: 'FUNCINFO_FUNCCODE',
                  value: state.formState.funcCode,
                  type: '=',
                  cn: 'and',
                },
              ],
            }),
          };

          let result = await FuncDetail(params).then((res) => {
            if (res.length === 0) {
              Modal.alert('功能不存在！');
            } else {
              return res[0];
            }
          });

          return result;
        },

        //根据功能id获得字段信息
        async getFuncField(funcId) {
          const params = {
            tableCode: 'JE_CORE_RESOURCECOLUMN',
            limit: -1,
            queryColumns: 'RESOURCECOLUMN_NAME,RESOURCECOLUMN_CODE',
            j_query: JSON.stringify({
              custom: [
                {
                  code: 'RESOURCECOLUMN_FUNCINFO_ID',
                  value: funcId,
                  type: '=',
                  cn: 'and',
                },
              ],
            }),
          };
          const columnObj = {};
          const columns = await FuncDetail(params).then((res) => {
            return res;
          });
          //封装成对象方便使用
          if (columns && columns.length > 0) {
            columns.forEach((item) => {
              columnObj[item.RESOURCECOLUMN_CODE] = item.RESOURCECOLUMN_NAME;
            });
          }
          return columnObj;
        },
        handleTranslate() {
          const params = {
            funcId: state.formState.RESOURCEFIELD_FUNCINFO_ID,
            sql: state.formState.RESOURCEFIELD_WHERESQL,
          };
          ChangeTranslateSql(params).then((res) => {
            state.formState.sqlRemark = res;

            // Modal.notice('操作成功', 'success');
          });
        },

        //回显带值规则列表数据
        async setTablesData(targetTable, oneselfTable) {
          //回显目标功能列表数据 codes
          if (isNotEmpty(targetTable)) {
            const targetTableDatas = [];
            const columnCodes = targetTable.split('~');
            //获得字段的信息,用于回显字段name
            const targetColums = await methods.getFuncField(state.formState.funcId);
            if (columnCodes && columnCodes.length > 0) {
              columnCodes.forEach((item, index) => {
                targetTableDatas.push({
                  code: item,
                  name: targetColums[item] || item,
                  index: index + 1,
                });
              });
            }
            if (targetTableDatas.length > 0) {
              state.codes.loadData(targetTableDatas);
            }
          }

          //回显本功能字段列表
          if (isNotEmpty(oneselfTable)) {
            const toneselfTableDatas = [];
            const columnCodes = oneselfTable.split('~');
            //获得字段的信息,用于回显字段name
            const toneselfColums = await methods.getFuncField(
              state.formState.RESOURCEFIELD_FUNCINFO_ID,
            );
            if (columnCodes && columnCodes.length > 0) {
              columnCodes.forEach((item, index) => {
                toneselfTableDatas.push({
                  code: item,
                  name: toneselfColums[item] || item,
                  index: index + 1,
                });
              });
            }
            if (toneselfTableDatas.length > 0) {
              state.selfCodes.loadData(toneselfTableDatas);
            }
          }
        },

        //回显数据
        async doDataPlayback() {
          const { RESOURCEFIELD_CONFIGINFO, RESOURCEFIELD_OTHERCONFIG } = state.formState;
          //获取功能编码
          const funcCode = 'JE_RBAC_VUSERQUERY';
          if (isNotEmpty(funcCode)) {
            //回显功能code
            state.formState.funcCode = funcCode;
            //根据功能编码获得功能id,name;
            let result = await methods.getFuncDetail();
            if (isNotEmpty(result)) {
              //回显功能id和name
              state.formState.funcName = result.FUNCINFO_FUNCNAME;
              state.formState.funcId = result.JE_CORE_FUNCINFO_ID;
            }
          }
          //给目标功能的列表赋默认值
          const targetDatas = [
            { code: 'USER_NAME', name: '用户名称', index: 1 },
            { code: 'USER_ID', name: '用户_ID', index: 2 },
            // { code: 'USERCODE', name: '帐号(登录)', index: 3 },
          ];
          state.codes.loadData(targetDatas);

          //根据配置信息回显数据
          const cfgs = RESOURCEFIELD_CONFIGINFO ? RESOURCEFIELD_CONFIGINFO.split(',') : '';
          if (isNotEmpty(cfgs)) {
            //回显选择方式
            const selModel = cfgs[3];
            state.formState.selModel = isNotEmpty(selModel) ? selModel : 'S';
            //回显带值规则
            await methods.setTablesData(cfgs[2], cfgs[1]);
          } else {
            state.formState.selModel = 'S';
          }
          //回显辅助配置项 RESOURCEFIELD_OTHERCONFIG
          const config = decode(RESOURCEFIELD_OTHERCONFIG ?? '{}') ?? {};
          state.otherCfgs = config;
          //queryType 过滤方式
          state.formState.deptQuery = config.deptQuery || '';
          state.formState.roleQuery = config.roleQuery || '';
          state.formState.organQuery = config.organQuery || '';
          state.formState.queryType = config.queryType || '';
          state.formState.querySqlDesc = config.querySqlDesc || '';
          //pkName 唯一
          const pkName = config.pkName || '';
          if (isNotEmpty(pkName)) {
            state.codes.data.forEach((item) => {
              if (item.code == pkName) {
                item.pkName = true;
              } else {
                item.pkName = false;
              }
            });
          }
        },
      };
      watch(
        () => state.formState,
        () => {
          if (state.formState.queryType && state.formState.queryType.split(',').length == 4) {
            const newQueryType = state.formState.queryType.split(',').splice(0, 3);
            nextTick(() => {
              state.formState.queryType = newQueryType.join(',');
            });
            Modal.alert('禁用过滤方式不允许全部禁用！', 'info');
          }
        },
        { deep: true },
      );
      onMounted(async () => {
        methods.doDataPlayback();
      });

      return {
        ...toRefs(state),
        ...methods,
        modalOption,
      };
    },
  });
</script>
<style lang="less" scoped>
  .people-choose-value-config {
    .inputWrap {
      position: relative;
      .setIcon {
        position: absolute;
        top: 50%;
        right: 10px;
        transform: translate(0, -50%);
        cursor: pointer;
      }
    }
    .iconWrap {
      cursor: pointer;
    }
    .tableWrap {
      display: flex;
      justify-content: space-between;
      height: 100%;
      .table {
        width: 48%;
      }
    }
  }
</style>
